'use client';

import React, { useState } from 'react';
import { getSesstion } from '@/lib/session';

// 自定义图标组件
const PlusOutlined = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
  </svg>
);

interface Props {
  changeSearch: (args: any) => void;
}

interface FileType {
  uid: string;
  name: string;
  status?: string;
  url?: string;
  preview?: string;
  originFileObj?: File;
}

const VectorForm: React.FC<Props> = ({ changeSearch }) => {
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [fileList, setFileList] = useState<FileType[]>([]);
  const [text, setText] = useState('');

  const getBase64 = (file: File): Promise<string> =>
    new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = (error) => reject(error);
    });

  const handlePreview = async (file: FileType) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as File);
    }

    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
  };

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files) return;

    const newFileList: FileType[] = [...fileList];

    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      const newFile: FileType = {
        uid: Date.now() + i.toString(),
        name: file.name,
        originFileObj: file,
      };

      try {
        newFile.preview = await getBase64(file);
      } catch (error) {
        console.error('Error getting base64:', error);
      }

      newFileList.push(newFile);
    }

    setFileList(newFileList);
  };

  const handleRemove = (file: FileType) => {
    setFileList(fileList.filter(item => item.uid !== file.uid));
  };

  const onFinish = () => {
    const formdata = new FormData();
    if (text) formdata.append('text', text);
    if (fileList.length) {
      fileList.forEach((item) => {
        if (item.originFileObj) {
          formdata.append('file', item.originFileObj);
        }
      });
    }
    changeSearch(formdata);
  };

  return (
    <div className="max-w-3xl mx-auto p-4">
      <form className="space-y-6">
        {/* 查询输入框 */}
        <div className="grid grid-cols-12 gap-4 items-center">
          <label htmlFor="text" className="col-span-3 text-right font-medium text-gray-700">
            查询
          </label>
          <div className="col-span-9">
            <input
              id="text"
              type="text"
              value={text}
              onChange={(e) => setText(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              placeholder="请输入查询内容"
            />
          </div>
        </div>

        {/* 图片上传 */}
        <div className="grid grid-cols-12 gap-4 items-start">
          <label className="col-span-3 text-right font-medium text-gray-700 pt-2">
            图片
          </label>
          <div className="col-span-9">
            <div className="border border-dashed border-gray-300 rounded-lg p-4">
              <div className="flex flex-wrap gap-3">
                {/* 已上传文件预览 */}
                {fileList.map((file) => (
                  <div key={file.uid} className="relative w-20 h-20 group">
                    <img
                      src={file.preview as string}
                      alt={file.name}
                      className="w-full h-full object-cover rounded border border-gray-200"
                      onClick={() => handlePreview(file)}
                    />
                    <button
                      type="button"
                      onClick={() => handleRemove(file)}
                      className="absolute top-0 right-0 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
                    >
                      <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                      </svg>
                    </button>
                  </div>
                ))}

                {/* 上传按钮 */}
                {fileList.length < 8 && (
                  <label className="flex flex-col items-center justify-center w-20 h-20 border border-dashed border-gray-300 rounded cursor-pointer bg-gray-50 hover:bg-gray-100 transition-colors">
                    <input
                      type="file"
                      multiple
                      accept="image/*"
                      onChange={handleFileChange}
                      className="hidden"
                    />
                    <PlusOutlined />
                    <span className="text-xs text-gray-500 mt-1">上传</span>
                  </label>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* 提交按钮 */}
        <div className="grid grid-cols-12 gap-4">
          <div className="col-span-9 col-start-4">
            <div className="flex space-x-4">
              <button
                type="button"
                onClick={onFinish}
                className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
              >
                Submit
              </button>
            </div>
          </div>
        </div>
      </form>

      {/* 图片预览模态框 */}
      {previewOpen && previewImage && (
        <div className="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50 p-4">
          <div className="relative max-w-4xl max-h-[90vh] overflow-auto">
            <img
              src={previewImage}
              alt="Preview"
              className="max-w-full max-h-[90vh] object-contain"
            />
            <button
              type="button"
              onClick={() => setPreviewOpen(false)}
              className="absolute top-4 right-4 bg-white rounded-full p-2 hover:bg-gray-100 transition-colors"
            >
              <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default VectorForm;
